package org.sunyaxing.transflow.agent.agentplugin;

import org.sunyaxing.transflow.api.netty.DataTransor;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;

public class TransflowBootstrap {
    private static TransflowBootstrap transflowBootstrap;
    private static Instrumentation instrumentation;
    private static ClassFileTransformer classFileTransformer;
    public static Boolean installed = false;
    public static DataTransor dataTransor;

    public TransflowBootstrap(Instrumentation instrumentation) {
        TransflowBootstrap.instrumentation = instrumentation;
    }

    public static TransflowBootstrap getInstance(Instrumentation instrumentation) {
        if (transflowBootstrap == null) {
            transflowBootstrap = new TransflowBootstrap(instrumentation);
            dataTransor = DataTransor.Builder.builder().host("127.0.0.1").port(18988).build();
            dataTransor.connect();
        }
        TransflowBootstrap.installed = true;
        return transflowBootstrap;
    }

    public static Instrumentation getInstrumentation() {
        return instrumentation;
    }

    public static void setClassFileTransformer(ClassFileTransformer classFileTransformer) {
        TransflowBootstrap.classFileTransformer = classFileTransformer;
    }

    public static void destory() {
        instrumentation.removeTransformer(classFileTransformer);
        classFileTransformer = null;
        transflowBootstrap = null;
        dataTransor.disconnect();
        dataTransor = null;
        OrgClassByteManager.restore(instrumentation);
        TransflowBootstrap.installed = false;
    }

    public static void send(String string) {
        if (dataTransor != null) {
            dataTransor.send(string);
        }
    }
}
